package com.orangelife.mobile.surrounding.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.PopupWindow;

import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.ScreenUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.util.LogE;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.surrounding.adapter.MerchantTypeAdapter;
import com.orangelife.mobile.surrounding.biz.SurroundHttpBiz;
import com.orangelife.mobile.surrounding.entity.MerchantTypeEntity;

import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 商户分类
 *
 * create:绯若虚无 160122
 * modify:
 * @author 绯若虚无
 * @since v3.4
 */
public class MerClassifyPopWin extends PopupWindow {

    private Context context;
    private List<MerchantTypeEntity> data = new ArrayList<>();
    private GridView gridView;
    EmptyLayout emptyLayout;
    public OnPopupWindowItemClickListener listener;
    private MerchantTypeAdapter adapter;

    /** 顶部栏+底部栏的高度 */
    private int mOverHeight;

    /**
     * 构造方法
     */
    public MerClassifyPopWin(Context context, int topBarHeight, int bottomHeight) {
        super(context);
        this.context = context;
        this.mOverHeight = topBarHeight + bottomHeight;
        request();
        initView();
    }

    /**
     * 请求商户分类列表
     */
    private void request() {
        SurroundHttpBiz.getMerchantTypeList(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                emptyLayout.dismiss();
                data = SurroundHttpBiz.handleMerchantTypeList(response, errCode);
                if (data != null && data.size() > 0) {
                    adapter.setList(data);
                    adapter.notifyDataSetChanged();
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NODATA);
                }
            }
        });
    }

    /**
     * 初始化popupwindow
     */
    private void initView() {
        View contentView = LayoutInflater.from(context).inflate(
                R.layout.popwin_mer_classify, null);
        setContentView(contentView);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        int screenHeight = ScreenUtil.getScreenHeight(context);
        int virtualHeight = (getDpi() - screenHeight);
        setHeight(screenHeight - mOverHeight - getStatusBarHeight());
        LogE.E("screenHeight = " + screenHeight + "，mOverHeight = " + mOverHeight + ", virtualHeight = " + virtualHeight);
        /* 设置popupwindow的基本属性 */
        gridView = (GridView) contentView.findViewById(R.id.gridView);
        emptyLayout = (EmptyLayout) contentView.findViewById(R.id.emptyLayout);
        setAdapter();
        //transparent
        setBackgroundDrawable(new ColorDrawable(context.getResources().getColor(R.color.btn_red)));
        setFocusable(true);

        /* 设置捕获popupwindow外的点击焦点 */
        setOutsideTouchable(true);
        setTouchInterceptor(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    dismiss();
                    return true;
                }
                return false;
            }
        });
        setListener();
    }


    /**
     * 载入列表item
     */
    private void setAdapter() {
        adapter = new MerchantTypeAdapter(context, data);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                listener.onPopupWindowItemClick(position, data.get(position).getIndustryConfigID(), data.get(position).getIndustryName());
                dismiss();
            }
        });
    }

    private void setListener() {
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request();
            }
        });
    }

    /**
     * 设置popupwindow的适配器
     */
    public void setOnPopupWindowClickListener(
            OnPopupWindowItemClickListener listener) {
        this.listener = listener;
    }

    /**
     * 为列表的item添加监听
     */
    public interface OnPopupWindowItemClickListener {
        void onPopupWindowItemClick(int clickPositon, String strItemData, String industryName);

        void onDismiss();
    }

    private int dip2px(float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private int getStatusBarHeight() {
        Rect frame = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        if (statusBarHeight == 0) {
            statusBarHeight = getBarHeight();
        }
        return statusBarHeight;
    }

    public int getBarHeight() {
        Class<?> c;
        Object obj;
        Field field;
        int x;
        int sbar = 38;//默认为38，貌似大部分是这样的

        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = (context).getResources().getDimensionPixelSize(x);

        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sbar;
    }

    private int getDpi() {
        int dpi = 0;
        Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            dpi = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (listener != null) {
            listener.onDismiss();
        }
    }
}